package com.geostar.constructionland.attachment.util;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FilenameUtils;
import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;

public class PdfHandler {
    
    public static File getOnePart(File file, int startPage, int endPage) {
        PDDocument document = null;
        File partFile = null;
        try {
            String filename = file.getCanonicalPath();
            String partFilename = FilenameUtils.removeExtension(filename) + "_" + startPage +"-"+ endPage + "." + FilenameUtils.getExtension(filename);
            document = PDDocument.load(file);
            List<PDDocument> parts = split(document, startPage, endPage, null);
            partFile = new File(partFilename);
            parts.get(0).save(partFile);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (document != null) {
                    document.close();
                }
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
        return partFile;
    }
    
    private static List<PDDocument> split(PDDocument document, Integer startPage, Integer endPage, Integer splitAtPage) {
        Splitter splitter = new Splitter();
        int aNumberOfPages = document.getNumberOfPages();
        boolean startEndPageSet = false;
        if (startPage != null) {
            splitter.setStartPage(startPage);
            startEndPageSet = true;
            if (splitAtPage == null) {
                splitter.setSplitAtPage(aNumberOfPages);
            }
        }
        if (endPage != null) {
            splitter.setEndPage(endPage);
            startEndPageSet = true;
            if (splitAtPage == null) {
                splitter.setSplitAtPage(endPage);
            }
        }
        if (splitAtPage != null) {
            splitter.setSplitAtPage(splitAtPage);
        }
        else if (!startEndPageSet) {
            splitter.setSplitAtPage(1);
        }
        List<PDDocument> parts = null;
        try {
            parts = splitter.split(document);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return parts;
    }
    
    public static void main(String[] args) {
        File file = new File("C:\\Users\\Jimmy\\Desktop\\测试文件\\粤国土资科教函.pdf");
        getOnePart(file, 1, 3);
    }
    
}
